<template>
  <!-- 知识库-模板管理 -->
  <div class="template-management">
    <a-card class="card-one" title="文件查询">
      <div class="input-box">
        <div class="item">
          <div class="text">文件类型</div>
          <a-select
            class="input"
            placeholder="请选择"
            v-model:value="formData.fileType"
          >
            <a-select-option
              v-for="item in templateTypeList"
              :key="item"
              :value="item"
              >{{ item }}</a-select-option
            >
          </a-select>
        </div>
        <div class="item">
          <a-button class="button" @click="clickReset">重置</a-button>
          <a-button type="primary" @click="clickQuery">查询</a-button>
        </div>
      </div>
    </a-card>
    <a-card class="card-two" title="文件列表">
      <template #extra>
        <a-upload
          v-model:file-list="fileList"
          :showUploadList="false"
          name="file"
          :action="rootUrl + api.tamplateUploadUrl"
          :headers="headers"
          @change="changeTamplateUpload"
        >
          <a-button type="primary">模板上传</a-button>
        </a-upload>
      </template>
      <a-table
        class="table"
        :pagination="false"
        :columns="columns"
        :data-source="tableData"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'operation'">
            <div class="operation">
              <a href="javascript:;" @click="clickOperation('下载', record)">
                下载
              </a>
              <a-popconfirm
                title="确认删除吗？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="clickOperation('删除', record)"
              >
                <a href="javascript:;"> 删除 </a>
              </a-popconfirm>
            </div>
          </template>
        </template>
      </a-table>
      <a-pagination
        v-model:current="formData.pageNum"
        v-model:pageSize="formData.pageSize"
        :total="formData.total"
        show-less-items
        @change="changePagination"
      />
    </a-card>
  </div>
</template>
<script setup>
  // 引入
  import {
    defineProps,
    defineEmits,
    h,
    watch,
    onMounted,
    onBeforeUnmount,
    ref,
  } from 'vue'
  import api from '@/axios/api.js'
  import { message } from 'ant-design-vue'
  import commonMethod from '@/common-method/common-method'
  const props = defineProps({})
  const emits = defineEmits([])
  // 数据
  const formData = ref({
    pageNum: 1,
    pageSize: 10,
    total: 0,
    fileType: undefined,
  })
  const headers = ref({})
  const rootUrl = import.meta.env.VITE_APP_URL
  const columns = [
    { title: '文件名称', dataIndex: 'templateName' },
    { title: '创建人', dataIndex: 'createBy' },
    { title: '创建时间', dataIndex: 'createTime' },
    { title: '操作', dataIndex: 'operation' },
  ] //列表配置
  const tableData = ref([]) //表格数据
  const fileList = ref([])
  const templateTypeList = ref([]) //模板类型列表
  // 生命周期
  onMounted(() => {
    //设置请求头
    function getCookie(name) {
      const cookies = document.cookie.split(';')
      for (let cookie of cookies) {
        const [key, value] = cookie.trim().split('=')
        if (key === name) {
          return decodeURIComponent(value)
        }
      }
      return null // 未找到
    }
    const env = import.meta.env.VITE_APP_ENV
    let allCookies
    if (env === 'dev') {
      allCookies =
        'Online.3c9e656d1f13e0fc2cbc3af658e20243.ec4e12c5f62e28bc869ca2136e92fb2a.eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiI4VHJleUoxYzJWeVRtRnRaU0k2SW5sMWJuZGxhU0lzSW1sa0lqb2lNelFpTENKeVpXZHBiMjVKWkNJNklqQWlMQ0pwY0VGa1pISmxjM01pT2lJeE56SXVNVFl1TWpVMExqa2lmUT09RnBhWiIsImp0aSI6IjIwMjU1MSIsImlhdCI6MTc1Mzg2MTU0MH0.SckwxbGz7Z5zndiXP7pBeLjX_HyLA1YiDR3jFJqiIrJxniYTznV5xyVURhXIIVdy8Mx-hhIQ0ovJ_T_vfvw8Ew; Path=/; SameSite=Lax;'
    } else if (env === 'pro') {
      allCookies = getCookie('X-Subject-Token')
    }
    headers.value = {
      authorization: `Bearer ${allCookies}`,
    }
    getTemplateList(formData.value)
    getTemplateTypeList()
  })
  // 方法
  //获取模板列表
  const getTemplateList = async (data) => {
    const res = await api.getTemplateList(data)
    console.log('获取模板列表', res)
    tableData.value = res.data.data.records
    formData.value.total = res.data.data.total
  }
  //获取模板类型列表
  const getTemplateTypeList = async (data) => {
    const res = await api.getTemplateTypeList(data)
    console.log('获取模板类型列表', res)
    templateTypeList.value = res.data.data
  }
  //删除模板列表
  const delTemplateList = async (data) => {
    const res = await api.delTemplateList(data)
    console.log('删除模板列表', res)
    if (res.data.code === 200) {
      message.success(`删除成功`)
      getTemplateList(formData.value)
    } else {
      message.error(`删除失败`)
    }
  }
  //文件批量下载
  const batchDownloadFiles = async (data) => {
    const res = await api.batchDownloadFiles(data)
    if (res.status === 200) {
      commonMethod.derive(res)
    } else {
      message.error(res.data.msg)
    }
  }
  //上传模板列表改变
  const changeTamplateUpload = (info) => {
    if (info.file.status === 'done') {
      message.success(`上传成功`)
      getTemplateList(formData.value)
    } else if (info.file.status === 'error') {
      message.error(`上传失败`)
    }
  }
  //点击重置
  const clickReset = () => {
    formData.value = {
      pageNum: 1,
      pageSize: 10,
      total: 0,
      fileType: undefined,
    }
    getTemplateList(formData.value)
  }
  //点击查询
  const clickQuery = () => {
    getTemplateList(formData.value)
  }
  //分页改变
  const changePagination = () => {
    getTemplateList(formData.value)
  }
  const clickOperation = (value, record) => {
    if (value === '删除') {
      delTemplateList([record.id])
    } else if (value === '下载') {
      batchDownloadFiles({
        fileIds: [record.fileId],
        fileName: record.fileName,
      })
    }
  }
</script>
<style lang="less" scoped>
  .template-management {
    .card-one {
      margin-bottom: (20 / @vh);
      .input-box {
        display: flex;
        gap: (20 / @vw);
        .item {
          display: flex;
          align-items: center;
          gap: (10 / @vw);
          width: 25%;
          .input {
            flex: 1;
          }
        }
      }
    }
    .card-two {
      .table {
        margin-bottom: (20 / @vh);
      }
    }
  }
</style>
